// API工具类
const api = {
  // 基础URL
  baseURL: 'http://localhost:9000',
  
  // MedusaJS publishable API key
  publishableApiKey: 'pk_f9ce46eebfed02c57668468fd01019e68fb864a49b5cc4f373e8f8d18d8aadbf',
  
  // 请求封装
  request(url, method, data) {
    return new Promise((resolve, reject) => {
      const token = uni.getStorageSync('token');
      
      uni.request({
        url: this.baseURL + url,
        method: method,
        data: data,
        header: {
          'Content-Type': 'application/json',
          'Authorization': token ? `Bearer ${token}` : '',
          'x-publishable-api-key': this.publishableApiKey
        },
        success: (res) => {
          // 检查HTTP状态码
          if (res.statusCode >= 200 && res.statusCode < 300) {
            resolve(res.data);
          } else {
            reject(new Error(`HTTP错误: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },
  
  // 微信小程序登录
    loginWithCode(code, encryptedData = null, iv = null) {
      return this.request('/store/auth/wechat-miniprogram/login', 'POST', {
        code: code,
        encryptedData: encryptedData,
        iv: iv
      });
    },
  
  // 获取用户信息
  getUserInfo() {
    return this.request('/store/customers/me', 'GET');
  },
  
  // 更新用户信息
  updateUserInfo(userInfo) {
    return this.request('/store/customers/me', 'PUT', userInfo);
  },
  
  // 获取用户地址列表
  getAddresses() {
    return this.request('/store/customers/me/addresses', 'GET');
  },
  
  // 添加用户地址
  addAddress(address) {
    return this.request('/store/customers/me/addresses', 'POST', address);
  },
  
  // 更新用户地址
  updateAddress(addressId, address) {
    return this.request(`/store/customers/me/addresses/${addressId}`, 'POST', address);
  },
  
  // 删除用户地址
  deleteAddress(addressId) {
    return this.request(`/store/customers/me/addresses/${addressId}`, 'DELETE');
  },
  
  // 获取商品列表
  getProducts(params = {}) {
    const queryString = Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`).join('&');
    return this.request(`/store/products${queryString ? '?' + queryString : ''}`, 'GET');
  },
  
  // 获取商品详情
  getProductDetail(id) {
    return this.request(`/store/products/${id}`, 'GET');
  },
  
  // 获取商品分类
  getCategories() {
    return this.request('/store/product-categories', 'GET');
  },
  
  // 创建购物车
  createCart() {
    return this.request('/store/carts', 'POST');
  },
  
  // 添加商品到购物车
  addToCart(cartId, variantId, quantity = 1) {
    return this.request(`/store/carts/${cartId}/line-items`, 'POST', {
      variant_id: variantId,
      quantity: quantity
    });
  }
};

export default api;